package sto.orz.server;

import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.Host; //import org.apache.catalina.Logger;
import org.apache.catalina.startup.Embedded;

/**
 * 还不实用,错误多,需要改造.
 */
public class Tomcat {
	public static void main(String[] args) {
		// 设置Tomcat的工作目录，并启动Tomcat Server
		String path = "D:/rptp/apache-tomcat-5.5.20-embed";
		Embedded tc = createTomcat(path);
		try {
			tc.start();
			System.out
					.println("---------- Tomcat Server start over. ------------");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static Embedded createTomcat(String path) {
		// 创建嵌入式Tomcat Server的实例
		Embedded tomcat = new Embedded();
		// 设置Tomcat的工作目录
		tomcat.setCatalinaHome(path);
		// 产生Tomcat引擎
		Engine engine = tomcat.createEngine();
		engine.setName("TestServer");
		// 创建Host，设置Host的工作目录
		Host host = tomcat.createHost("localhost", "d:/rptp/trunk/rptp/src/main/webapp");
		// 把Host加入Engine
		engine.addChild(host);
		engine.setDefaultHost(host.getName());

		String javayouPath = ".";
		if (!new File(javayouPath).exists()) {
			System.err.println("请检查Javayou应用的目录以及相关资源是否存在.");
			return null;
		}
		// 创建Javayou的Context，并加入Host中
		Context ctxtJavayou = tomcat.createContext("/rptps3", javayouPath);
		host.addChild(ctxtJavayou);

		tomcat.addEngine(engine);
		//tomcat.setDebug(Logger.WARNING);
		try {
			// Tomcat加入Connector，监听本地（127.0.0.1）的访问
			tomcat.addConnector(tomcat.createConnector(InetAddress
					.getByName("127.0.0.1"), 8080, false));
		} catch (UnknownHostException e) {
			System.err.println("绑定Tomcat Server到127.0.0.1:8080失败，请检查端口是否被占用.");
			e.printStackTrace();
			tomcat = null;
		}
		return tomcat;
	}
}